import ctypes
import struct
import win32api
import  time
from module.public import find_pid_by_name, get_module_base_address

PROCESS_ALL_ACCESS = (0x000F0000 | 0x00100000 | 0xFFF)

def get_process_handle():
    process_name = "PlantsVsZombiesRH.exe"
    pid = find_pid_by_name(process_name)
    if pid:
        print("pid",pid,win32api.OpenProcess(PROCESS_ALL_ACCESS, False, pid))
        return win32api.OpenProcess(PROCESS_ALL_ACCESS, False, pid)
    return None

def read_memory(process_handle, address, size):
    buffer = ctypes.create_string_buffer(size)
    bytes_read = ctypes.c_size_t()
    kernel32 = ctypes.windll.kernel32
    if not kernel32.ReadProcessMemory(int(process_handle), ctypes.c_void_p(address), buffer, size, ctypes.byref(bytes_read)):
        raise Exception(f"Could not read memory: {ctypes.WinError()}")
    return buffer.raw

def write_memory(process_handle, address, data):
    size = len(data)
    buffer = ctypes.create_string_buffer(data)
    bytes_written = ctypes.c_size_t()
    kernel32 = ctypes.windll.kernel32
    if not kernel32.WriteProcessMemory(int(process_handle), ctypes.c_void_p(address), buffer, size, ctypes.byref(bytes_written)):
        raise Exception(f"Could not write memory: {ctypes.WinError()}")
    return bytes_written.value

def modify_sunlight(value):
    process_handle = get_process_handle()
    if process_handle:
        try:
            base_address = get_module_base_address(find_pid_by_name("PlantsVsZombiesRH.exe"), "UnityPlayer.dll")
            sun_base_address = base_address + 0x01D304F8
            offsets = [0x0, 0x460, 0x0, 0x10, 0x30, 0x38, 0x28, 0x60]

            current_address = sun_base_address
            for offset in offsets:
                current_address = struct.unpack("Q", read_memory(process_handle, current_address, 8))[0] + offset

            write_memory(process_handle, current_address, struct.pack("I", value))

        except Exception as e:
            print(f"An error occurred: {e}")
        finally:
            win32api.CloseHandle(process_handle)

def infinite_sunlight():
    process_handle = get_process_handle()
    if process_handle:
        try:
            base_address = get_module_base_address(find_pid_by_name("PlantsVsZombiesRH.exe"), "UnityPlayer.dll")
            sun_base_address = base_address + 0x01D304F8
            offsets = [0x0, 0x460, 0x0, 0x10, 0x30, 0x38, 0x28, 0x60]

            current_address = sun_base_address
            for offset in offsets:
                current_address = struct.unpack("Q", read_memory(process_handle, current_address, 8))[0] + offset

            while True:
                write_memory(process_handle, current_address, struct.pack("I", 9999))
                time.sleep(1)

        except Exception as e:
            print(f"An error occurred: {e}")
        finally:
            win32api.CloseHandle(process_handle)
